import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// import Login from '../views/Login/Login.vue'
// // @ 符号在路径中表示 src 的绝对路径, 脚手架为我们配置的
// import Reg from '@/views/Reg/Reg.vue'
// import Main from '@/views/Main/Main.vue'
// import Home from '@/views/Menus/Home/Home.vue'
// import UserInfo from '@/views/Menus/User/UserInfo.vue'
// import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
// import UserPwd from '@/views/Menus/User/UserPwd.vue'
// import ArtCate from '@/views/Menus/Article/ArtCate.vue'
// import ArtList from '@/views/Menus/Article/ArtList.vue'
const Login = () => import('../views/Login/Login.vue')
// @ 符号在路径中表示 src 的绝对路径, 脚手架为我们配置的
const Reg = () => import('@/views/Reg/Reg.vue')
const Main = () => import('@/views/Main/Main.vue')
const Home = () => import('@/views/Menus/Home/Home.vue')
const UserInfo = () => import('@/views/Menus/User/UserInfo.vue')
const UserAvatar = () => import('@/views/Menus/User/UserAvatar.vue')
const UserPwd = () => import('@/views/Menus/User/UserPwd.vue')
const ArtCate = () => import('@/views/Menus/Article/ArtCate.vue')
const ArtList = () => import('@/views/Menus/Article/ArtList.vue')

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

// 路由规则数组
const routes = [
  // 一个对象表示一条规则
  {
    path: '/login',
    component: Login
  },
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/',
    component: Main,
    // 重定向到 /home
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'user-info',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        component: UserAvatar
      },
      {
        path: 'user-pwd',
        component: UserPwd
      },
      {
        path: 'art-cate',
        component: ArtCate
      },
      {
        path: 'art-list',
        component: ArtList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 使用导航守卫, 进行未登录的权限控制
// to: 到哪里去
// from: 从哪里来
// next: 是否放行, 函数, 调用不传参表示放行, 调用传入 false 表示不放行, 传入 path 可以强行跳转至指定路径
router.beforeEach((to, from, next) => {
  // 在特定的条件下强制跳转至 /login
  // 条件1: 未登录, 没有 token
  // 条件2: 要去的页面不是 /login 和 /reg (白名单)
  // 如果未登录时允许访问的页面很多, 需要在后面继续加 && 判断条件, 这样代码美观度较低, 语法也不够精简, 属于某内某鸟的代码
  // if (!store.state.user.token && to.path !== '/login' && to.path !== '/reg') {
  // 白名单: 不管登没登录都可以访问的页面
  // 高级的代码
  const whiteList = ['/login', '/reg']
  // includes: 包含, 判断指定的元素是否在数组中
  if (!store.state.user.token && !whiteList.includes(to.path)) {
    // 给用户一个友好的提示
    Vue.prototype.$message.error('您没登录啊傻子!')
    return next('/login')
  }
  next()
})

export default router
